package core;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.Remote;
import java.rmi.RemoteException;

public class CentralServer {
	private String hostname;
	private String port;
	
	public CentralServer(String hostname, String port){
		this.hostname = hostname;
		this.port = port;
	}
	
	public String bind(String name, Remote object) throws RemoteException, MalformedURLException{
		String url = "rmi://"+hostname+":"+port+"/"+name;
		Naming.rebind(url, object);
		//LocateRegistry.getRegistry(port).rebind(name, object);
		return name+" bound to "+url;
	}
	
	//both args are optional, first arg is port, second is debug
	public static void main(String args[]){
		String hostname = "localhost", port, name = "PizzaStoreFacade";
		
		if(args.length > 0){
			port = args[0];
		}else{
			port = "1099";//default port
		}
		
		try {
			java.rmi.registry.LocateRegistry.createRegistry(Integer.parseInt(port));
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.err.println("Invalid port: "+port);
			System.exit(-1);
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		CentralServer server = new CentralServer(hostname,port);
		
		try {
			CentralTracker tracker = new CentralTracker();
			String message = "";
			if(args.length>1){
				message = server.bind(name, new PizzaStoreFacade(tracker, true));
			}
			else{
				message = server.bind(name, new PizzaStoreFacade(tracker, false));
			}
			
			System.out.println(message);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
